package com.zoho.aimei.service;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoho.aimei.utils.BooksApiUtil;
import com.zoho.aimei.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SynServiceImpl implements SynService {

    BooksApiUtil booksApiUtil;

    public SynServiceImpl(BooksApiUtil booksApiUtil) {
        this.booksApiUtil = booksApiUtil;
    }


    @Override
    public void synData() {

        // 1 获取官方数据
        String startTime = DateUtil.getPrevious3DaysDate();
        //String startTime = DateUtil.getToday();
        System.out.println("startTime = " + startTime);
        List<JSONObject> originData = getOriginData(startTime);
        System.out.println("官方数据 = " + originData.size());

        // 2 books 数据
        List<JSONObject> books_allItemList = booksApiUtil.getAllItemList();
        //System.out.println("books_allItemList.size() = " + books_allItemList.size());

        // 3 处理官方数据
        // 倒序遍历，因为官方的接口数据，最新的数据在第一个，所以要倒序
        for (int i = originData.size() - 1; i >= 0; i--) {
            JSONObject origin = originData.get(i);
            //String number = origin.getString("number");
            //if (!number.equals("2025112521545400245")) {
            //    continue;
            //}

            // 4 验证item
            // 临时productList，用来存官方接口数据的product，以及添加到books item以后的数据id
            List<JSONObject> tempProductList = new ArrayList<>();
            JSONArray products = origin.getJSONArray("products");
            List<String> itemIdList = new ArrayList<>();
            if (products.size() > 0) {
                List<JSONObject> productList = products.toJavaList(JSONObject.class);
                for (JSONObject product : productList) {
                    String sku = product.getString("number");
                    List<JSONObject> item_filter = books_allItemList.stream().filter(obj -> obj.getString("sku").equals(sku)).collect(Collectors.toList());
                    String item_id;
                    if (item_filter.size() > 0) {
                        item_id = item_filter.get(0).getString("item_id");
                        itemIdList.add(item_id + "_item");
                    } else {
                        // 新增item
                        item_id = pushItemData(product);
                        if (StringUtils.isNotBlank(item_id)) {
                            itemIdList.add(item_id + "_item");
                        }
                    }
                    JSONObject tempProduct = JSONObject.parseObject(product.toJSONString());
                    tempProduct.put("booksId", item_id);
                    tempProduct.put("type", "item"); // 类型是产品
                    tempProductList.add(tempProduct);
                }
            }

            // 5 验证gift赠品，赠品有可能不存在于item中，所以要添加到item里
            JSONArray events = origin.getJSONArray("event");
            if (Objects.nonNull(events) && events.size() > 0) {
                List<JSONObject> eventList = events.toJavaList(JSONObject.class);
                for (JSONObject event : eventList) {
                    JSONArray gifts = event.getJSONArray("gift");
                    if (Objects.nonNull(gifts) && gifts.size() > 0) {
                        List<JSONObject> giftList = gifts.toJavaList(JSONObject.class);
                        for (JSONObject gift : giftList) {
                            String sku = gift.getString("number");
                            List<JSONObject> item_filter = books_allItemList.stream().filter(obj -> obj.getString("sku").equals(sku)).collect(Collectors.toList());
                            String item_id;
                            if (item_filter.size() > 0) {
                                item_id = item_filter.get(0).getString("item_id");
                                itemIdList.add(item_id + "_gift");
                            } else {
                                // 新增item
                                item_id = pushItemData(gift);
                                if (StringUtils.isNotBlank(item_id)) {
                                    itemIdList.add(item_id + "_gift");
                                }
                            }
                            JSONObject tempProduct = JSONObject.parseObject(gift.toJSONString());
                            tempProduct.put("booksId", item_id);
                            tempProduct.put("type", "gift"); // 类型是赠品
                            tempProductList.add(tempProduct);
                        }
                    }
                }
            }

            // 6 验证customer
            String customerId = "";
            JSONObject delivery = origin.getJSONObject("delivery");
            JSONObject invoice = origin.getJSONObject("invoice");
            String email = delivery.getString("email");
            List<JSONObject> books_allContactsList = booksApiUtil.getAllContactsListByEmail(email);
            List<JSONObject> customer_filter = books_allContactsList.stream().filter(obj -> obj.getString("email").equals(email)).collect(Collectors.toList());
            if (customer_filter.size() > 0) {
                String contact_name = customer_filter.get(0).getString("contact_name");
                customerId = customer_filter.get(0).getString("contact_id");
                // 更新数据
                pushCustomerData(delivery, invoice, contact_name, customerId);

            } else {
                // 新增 customer
                customerId = pushCustomerData(delivery, invoice, "", "");
            }

            // 7 验证sales order
            String saleOrderNum = origin.getString("number");
            List<JSONObject> books_allSaleOrderList = booksApiUtil.getAllSalesOrdersList();
            List<JSONObject> saleOrder_filter = books_allSaleOrderList.stream().filter(obj -> obj.getString("salesorder_number").equals(saleOrderNum)).collect(Collectors.toList());
            if (saleOrder_filter.size() == 0) {
                pushSaleOrderData(customerId, origin, itemIdList, tempProductList, books_allItemList);
            }
        }
    }


    // 获取第三方数据
    private List<JSONObject> getOriginData(String startTime) {
        int limit = 10;
        int page = 1;
        String baseUrl = "https://www.yamaybio.com/api/ordering/get_all?";
        List<JSONObject> resultList = new ArrayList<>();
        boolean flag;
        do {
            try {
                String url = baseUrl + "limit=" + limit + "&page=" + page + "&starttime=" + startTime;
                String body = HttpRequest.get(url).header("Authorization", "i2nEsRkESAtaymsTBDtY4jnFYaAxmFhH").execute().body();
                JSONObject result = JSONObject.parseObject(body);
                if (result.getInteger("code") != 1) {
                    log.error("查询官方接口失败url={}", url);
                    log.error("查询官方接口失败result={}", result.toJSONString());
                }
                JSONArray data = result.getJSONArray("data");
                resultList.addAll(data.toJavaList(JSONObject.class));
                Integer current_page = result.getInteger("current_page");
                Integer last_page = result.getInteger("last_page");
                flag = current_page < last_page;
                page++;
            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }

        } while (flag);

        return resultList;
    }

    private String pushItemData(JSONObject itemData) {
        //itemData.put("name", "zohoTest" + itemData.getString("title")); // todo
        itemData.put("name", itemData.getString("title"));
        itemData.put("sku", itemData.getString("number"));
        itemData.put("rate", itemData.getString("price"));
        List<JSONObject> custom_fields = new ArrayList<>();
        // data_source
        JSONObject cf_data_source = new JSONObject();
        cf_data_source.put("value", "Official_website");
        cf_data_source.put("api_name", "cf_data_source");
        custom_fields.add(cf_data_source);
        JSONObject cf_specification = new JSONObject();
        cf_specification.put("value", itemData.getString("specification"));
        cf_specification.put("api_name", "cf_specification");
        custom_fields.add(cf_specification);
        itemData.put("custom_fields", custom_fields);
        return booksApiUtil.insertItemData(itemData);
    }

    private String pushCustomerData(JSONObject delivery, JSONObject invoice, String contact_name, String customerId) {
        JSONObject contactData = new JSONObject();
        //contactData.put("contact_name", "zohoTest" + delivery.getString("full_name")); // todo
        //if(StringUtils.isNotBlank(contact_name)){
        //    contactData.put("contact_name", contact_name);
        //}else{
        //    contactData.put("contact_name", delivery.getString("full_name"));
        //}
        contactData.put("contact_name", delivery.getString("full_name"));
        List<JSONObject> custom_fields = new ArrayList<>();

        // email
        JSONObject email = new JSONObject();
        email.put("email", delivery.getString("email"));
        List<JSONObject> emailList = new ArrayList<>();
        emailList.add(email);
        contactData.put("contact_persons", emailList);

        // data_source
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("value", "Official_website");
        jsonObject.put("api_name", "cf_data_source");
        custom_fields.add(jsonObject);
        contactData.put("custom_fields", custom_fields);

        // billing_address
        JSONObject shipping_address = new JSONObject();
        shipping_address.put("attention", delivery.getString("full_name"));
        shipping_address.put("phone", delivery.getString("phone"));
        shipping_address.put("address", delivery.getString("detailed_address"));
        shipping_address.put("zip", delivery.getString("zip_code"));
        shipping_address.put("city", delivery.getString("city"));
        JSONObject state = delivery.getJSONObject("state");
        if (Objects.nonNull(state)) {
            shipping_address.put("state", state.getString("name_en"));
        }
        JSONObject nation = delivery.getJSONObject("nation");
        if (Objects.nonNull(nation)) {
            shipping_address.put("country", nation.getString("name_en"));
        }
        contactData.put("shipping_address", shipping_address);

        // shipping_address
        JSONObject billing_address = new JSONObject();

        billing_address.put("attention", invoice.getString("full_name"));
        billing_address.put("phone", invoice.getString("phone"));
        billing_address.put("address", invoice.getString("detailed_address"));
        billing_address.put("zip", invoice.getString("zip_code"));
        billing_address.put("city", invoice.getString("city"));
        JSONObject invoice_state = invoice.getJSONObject("state");
        if (Objects.nonNull(invoice_state)) {
            billing_address.put("state", invoice_state.getString("name_en"));
        }
        JSONObject invoice_nation = invoice.getJSONObject("nation");
        if (Objects.nonNull(invoice_nation)) {
            billing_address.put("country", invoice_nation.getString("name_en"));
        }
        contactData.put("billing_address", billing_address);

        if (StringUtils.isNotBlank(contact_name)) {
            return booksApiUtil.updateContactData(contactData, customerId);
        } else {
            return booksApiUtil.insertContactData(contactData);
        }

    }

    private void pushSaleOrderData(String customerId, JSONObject origin, List<String> itemIdList, List<JSONObject> tempProductList, List<JSONObject> books_allItemList) {
        String saleOrderNum = origin.getString("number");
        JSONObject fee = origin.getJSONObject("fee");

        //JSONObject tax = origin.getJSONObject("tax");
        JSONObject saleOrderData = new JSONObject();
        saleOrderData.put("customer_id", customerId);
        //saleOrderData.put("salesorder_number", "zohoTest" + saleOrderNum); // todo
        saleOrderData.put("salesorder_number", saleOrderNum);
        saleOrderData.put("shipping_charge", fee.getBigDecimal("delivery_fee"));
        saleOrderData.put("adjustment", fee.getBigDecimal("tax"));
        saleOrderData.put("adjustment_description", "Tax");
        //coupon_offer
        BigDecimal coupon_offer = fee.getBigDecimal("coupon_offer");
        BigDecimal event_offer = fee.getBigDecimal("event_offer");
        saleOrderData.put("has_discount", true);
        saleOrderData.put("is_discount_before_tax", true);
        saleOrderData.put("discount_type", "entity_level");
        saleOrderData.put("discount", coupon_offer.add(event_offer));

        // item
        List<JSONObject> itemList = new ArrayList<>();
        for (String item : itemIdList) {
            JSONObject itemJson = new JSONObject();

            String itemId = item.substring(0, item.indexOf("_"));
            String type = item.substring(item.indexOf("_") + 1);
            itemJson.put("item_id", itemId);
            itemJson.put("tax_exemption_code", "1"); // 进来的数据都默认不计税，即:sales order的item列表中，TAX字段为Non-Taxable
            if (type.equals("item")) {
                List<JSONObject> filter = tempProductList.stream().filter(obj ->
                        obj.getString("booksId").equals(itemId) && obj.getString("type").equals("item")).collect(Collectors.toList());
                if (filter.size() > 0) {
                    JSONObject temp = filter.get(0);
                    itemJson.put("quantity", temp.getString("quantity"));
                    itemJson.put("rate", temp.getString("price"));
                    itemList.add(itemJson);
                }
            } else if (type.equals("gift")) {
                List<JSONObject> filter = tempProductList.stream().filter(obj ->
                        obj.getString("booksId").equals(itemId) && obj.getString("type").equals("gift")).collect(Collectors.toList());
                if (filter.size() > 0) {
                    JSONObject temp = filter.get(0);
                    itemJson.put("quantity", temp.getString("num"));
                    itemJson.put("rate", 0);
                    itemList.add(itemJson);
                }

            }
            List<JSONObject> filter = tempProductList.stream().filter(obj -> obj.getString("booksId").equals(itemId)).collect(Collectors.toList());

        }
        saleOrderData.put("line_items", itemList);

        List<JSONObject> custom_fields = new ArrayList<>();
        // data_source
        JSONObject data_source = new JSONObject();
        data_source.put("value", "Official_website");
        data_source.put("api_name", "cf_data_source");
        custom_fields.add(data_source);
        saleOrderData.put("custom_fields", custom_fields);
        //System.out.println("saleOrderData.toJSONString() = " + saleOrderData.toJSONString());
        booksApiUtil.insertSaleOrderData(saleOrderData);
    }
}
